<?php defined('SYSPATH') or die('No direct script access.');

abstract class Controller_Abase_Acommon extends Controller_Template {

    public $offset;
    public $_config;
    public $form;
    public $pagination;
    public $settings;

    public function before() {
        parent::before();
        $this->_config = Kohana::$config->load('administration');
        $this->settings = Model::factory('Asettings')->getSettings();
        View::set_global('title', 'Zuber - админ панель');

        if (!Cookie::get('admin', null)) { // если нет сессии с админом то редиректим на страницу логина
            $this->redirect('administration/aauth');
            die();
        }

        View::set_global('frontAdmin', ORM::factory('Aadmins', array(
            'id' => Cookie::get('admin', null)
        )));

        $this->template->cur_date = date('d').' '.Model::factory('Afunctions')->parseMonth(date('m')).' '.date('Y');
        $this->template->admin_fio = $this->template->frontAdmin->fio;
        $this->template->settings = $this->settings;
        $this->template->leftmenu = View::factory('apieces/abase/leftmenu', array(
            'leftmenu' => $this->_config->get('leftmenu'),
            'controller' => $this->request->controller()
        ));
    }

    public function params() {
        return Model::factory($this->request->controller())->params();
    }

    public function dataListDefaults() {
        return array(
            'controller' => $this->request->controller(),
            'page' => $this->request->param('page'),
            'item_id' => $this->request->param('id'),
            'baseUrl' => URL::base()
        );
    }

    public function uploadImage($name, $oldFileName) {
        if (!empty($_FILES[$name]['tmp_name'])) {
            // Получение параметров для файла
            $imageParams = arr::path($this->params(), 'fields.'.$name.'.image_params');
            $thumbnails = arr::path($this->params(), 'fields.'.$name.'.thumbnails');
            $path = $imageParams['dir'];
            $ext = pathinfo($_FILES[$name]['name'], PATHINFO_EXTENSION);
            $hash = md5($_FILES[$name]['tmp_name']).time();

            if (!empty($oldFileName)) {
                $oldext = explode('.', $oldFileName);
                $fileName = $oldext[0].'.'.$ext;
            } else {
                $fileName = $hash.'.'.$ext;
            }

            // Сохранение файла
            if (!is_dir($path)) {
                mkdir($path, 0755);
            }

            $fullName = Upload::save($_FILES[$name], $fileName, $path);

            // Создание thumbnails
            if (!empty($thumbnails)) {
                foreach ($thumbnails as $key => $item) {
                    $thumbnail_dir = pathinfo($fullName, PATHINFO_DIRNAME).'/'.$key;

                    if (!is_dir($thumbnail_dir)) {
                        mkdir($thumbnail_dir, 0755);
                    }

                    $thumbnail_name = pathinfo($fullName, PATHINFO_DIRNAME).'/'.$key.'/'.pathinfo($fullName, PATHINFO_BASENAME);

                    if ($item['handling'] == 'crop') {
                        Image::factory($fullName)
                            ->crop($item['width'], $item['height'])
                            ->save($thumbnail_name, 100);
                    } elseif ($item['handling'] == 'resize') {
                        Image::factory($fullName)
                            ->resize($item['width'], $item['height'], $item['resize_type'])
                            ->save($thumbnail_name, 100);
                    } elseif ($item['handling'] == 'resize_crop') {
                        $image = Image::factory($fullName);
                        $ratio = $image->width / $image->height;
                        $original_ratio = $item['width'] / $item['height'];
                        $crop_width = $image->width;
                        $crop_height = $image->height;

                        if($ratio > $original_ratio) {
                            $crop_width = round($original_ratio * $crop_height);
                        } else {
                            $crop_height = round($crop_width / $original_ratio);
                        }

                        $image->crop($crop_width, $crop_height)->resize($item['width'], $item['height'], Image::NONE)->save($thumbnail_name, 100);
                        /*Image::factory($fullName)
                            ->resize($item['width'], $item['height'], $item['resize_type'])
                            ->crop($item['width'], $item['height'], TRUE, TRUE)
                            ->save($thumbnail_name, 100);*/
                    }
                }
            }

            // Оригинал
            if (empty($imageParams['original'])) {
                if ($imageParams['handling'] == 'crop') {
                    Image::factory($fullName)->crop($imageParams['width'], $imageParams['height'])->save();
                } elseif ($imageParams['handling'] == 'resize') {
                    Image::factory($fullName)->resize($imageParams['width'], $imageParams['height'], $imageParams['resize_type'])->save();
                } elseif ($imageParams['handling'] == 'resize_crop') {
                    Image::factory($fullName)
                        ->resize($imageParams['width'], $imageParams['height'], $imageParams['resize_type'])
                        ->crop($imageParams['width'], $imageParams['height'], TRUE, TRUE)
                        ->save();
                }
            }

            return $fileName;
        } else {
            return $oldFileName;
        }
    }

    public function deleteImages($field, $imageName) {
        $original = arr::path($this->params(), 'fields.'.$field.'.image_params');
        $thumbnails = arr::path($this->params(), 'fields.'.$field.'.thumbnails');

        if (is_file($original['dir'].'/'.$imageName)) {
            unlink($original['dir'].'/'.$imageName);
        }

        if (!empty($thumbnails)) {
            foreach ($thumbnails as $key => $item) {
                if (is_file($original['dir'].'/'.$key.'/'.$imageName)) {
                    unlink($original['dir'].'/'.$key.'/'.$imageName);
                }
            }
        }
    }

    public function showDefaultList() {
        $params = $this->params();
        $currentPage = $this->request->param('page');
        empty($params['view']) ? $params['view'] = 'apieces/abase/adefaultList' : FALSE;

        if ($currentPage == 1 || empty($currentPage)) {
            $this->offset = 0;
        }
        else {
            $this->offset = $currentPage*$this->_config->get('itemsPerPage')-$this->_config->get('itemsPerPage');
        }

        if (!empty($params['order'])) { // указываем поле сортировки при выводе списка (если нет, то сортируем по id DESC)
            $order_field = $params['order']['field'];
            $order_method = $params['order']['method'];
        } else {
            $order_field = 'id';
            $order_method = 'DESC';
        }

        $this->template->right = View::factory('apages/amain', array(
            'content' => View::factory('apieces/abase/adefaultContent', array(
                'list' => View::factory($params['view'], array(
                    'defaults' => $this->dataListDefaults(),
                    'data' => ORM::factory($this->request->controller())->order_by($order_field, $order_method)->limit($this->_config->get('itemsPerPage'))->offset($this->offset)->find_all(),
                    'params' => $params,
                    //'sortable' => !empty($params['sortable']) ? $sortable = TRUE : $sortable = FALSE,
                )),
                'form' => $this->form,
                'pagination' => $this->pagination
            )),
            'title' => $params['main_title'],
            'search_indexes' => !empty($params['search_indexes']) ? $params['search_indexes'] : '',
            'table' => $params['table'],
            'model' => $params['model'],
        ));
    }

    public function showPagination() {
        $this->pagination = Pagination::factory(array(
            'view' => 'pagination/admin',
            'total_items' => ORM::factory($this->request->controller())->count_all(),
            'items_per_page' => $this->_config->get('itemsPerPage'),
        ));
    }

    public function showDefaultForm($params, $obj, $action = 'add') { // массив с настройками для полей формы, объект для значений по умолчанию, action для формы
        if ($action == 'add') { // генерим ссылку для отправки формы
            $actionLink = '/administration/'.$this->request->controller().'/'.$this->request->param('page').'/add';
            $action = 'add';
            //$this->form = View::factory('apieces/addButton', array('text' => 'Добавить'));
        } else {
            $actionLink = '/administration/'.$this->request->controller().'/'.$this->request->param('page').'/edit/'.$this->request->param('id').'/save';
            $action = 'edit';
            //$this->form = View::factory('apieces/addButton', array('text' => 'Редактировать'));
        }

        $this->form .= View::factory('aforms/adefaultForm', array(
            'actionLink' => $actionLink,
            'params' => $params,
            'obj' => $obj,
            'action' => $action
        ));
    }

    public function saveToFile($fullName, $content) {
        $fp = fopen($fullName, 'w+');
        fwrite($fp, $content);
        fclose($fp);
    }
}